import { materialGetCapInfoApi } from "@Api/sysApi/materialApi"
import { getBrandList, getCatePropertyV2Api } from "@Api/sysApi/productApi"
import { Button, Icon, Modal, Space } from "@bytedance/mona-ui"
import { Agreement } from "@Utils/addConfigFuncs"
// import copyGoodsStyle from "@Styles/copyGoodsStyle.scss?inline"
import type {
  PlasmoCSConfig,
  PlasmoCSUIProps,
  PlasmoGetStyle,
  PlasmoMountShadowHost
} from "plasmo"
import type { FC } from "react"
import React, { useEffect, useState } from "react"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"

import { persistor, store, useAppDispatch, useAppSelector } from "~store"
import {
  setGoodsDetell,
  setneircunStatus
} from "~store/controller/jinritemaiCopyGoods"

import {
  getGoodsDetells,
  getJiebaApiData,
  getPrettifyFromUriData,
  getProductUpdateRuleData,
  getSearchWordApiData
} from "./copyDataFomate"
import CopyItemBox from "./copyItemBox"
import {
  weiguijianceContent
} from "~store/controller/funcTabs"
import { getVideoDetail, getVideoDetailNewApi } from '@Api/shopsApi'
// import {
//   addUserShopItem,
//   showPriceInfo
// } from "~store/controller/jinritemaiProduct"

// export const getStyle: PlasmoGetStyle = () => {
//   const style = document.createElement("style")
//   style.textContent = copyGoodsStyle
//   return style
// }
// 指定挂载站点
export const config: PlasmoCSConfig = {
  matches: ["https://fxg.jinritemai.com/*"]
}
export const getInlineAnchorList: any = async () => {
  const urls = location.pathname === "/ffa/g/list"
  if (!urls) return
  const detailList = document.querySelectorAll(
    "tbody > tr > [class*=style_operating]"
  )
  const elmList: any[] = []
  for (let i = 0; i < detailList.length; i++) {
    elmList.push(detailList[i].querySelector("div"))
  }
  return elmList
}
export const mountShadowHost: PlasmoMountShadowHost = ({
  shadowHost,
  anchor,
  mountState
}) => {
  anchor?.element.insertBefore(shadowHost, anchor.element.children[0])
  mountState?.observer?.disconnect() // OPTIONAL DEMO: stop the observer as needed
}

const ShowPriceUi = (props) => {
  const [showCopyBox, setShowCopyBox] = useState(false)
  const [getDataLodin, setDataLodin] = useState(true)
  const [goodsDetellData, setGoodsDetellData] = useState(null)
  const [goodPrettify, setGoodPrettify] = useState<string[]>([])
  const [goodPrettifyStatus, setGoodPrettifyStatus] = useState(false)
  const [titleJfrStart, setTitleJfrStart] = useState(null)
  const [searchWord, setSearchWord] = useState<any[]>([])
  const [searchWordMsg, setSearchWordMsg] = useState("")
  const [cateProperty, setCateProperty] = useState(null)
  const [showNercunM, setShowNercunM] = useState(false)
  const [ruleData, setRuleData] = useState<any>({})
  const [statsDataList, setStatsDataList] = useState<any[]>([])
  const [brandList, setBrandList] = useState<any[]>([])

  const dispatch = useAppDispatch()
  const showConetrBox = async () => {
    materialGetCapInfoApi().then((resa) => {
      // console.log('已使用容量，单位KB', resa.data.photo_capacity_used)
      // console.log('图片总容量，单位KB', resa.data.photo_capacity)
      // console.log('剩余', (resa.data.photo_capacity - resa.data.photo_capacity_used) / 1024 + 'm')
      // console.log('是否还可以创建', (resa.data.photo_capacity - resa.data.photo_capacity_used) / 1024 >= 50)
      if (
        (resa.data.photo_capacity - resa.data.photo_capacity_used) / 1024 <
        50
      ) {
        // console.log('提升不可以创建 要求清理')
        dispatch(setneircunStatus(false))
        setShowNercunM(true)
        return
      }
    })
    setShowCopyBox(true)
    setDataLodin(true)
    const gettiye = await Promise.all([
      getSearchWordApiData({
        product_id: props.goodid
      }),
      getSearchWordApiData({
        product_id: props.goodid,
        intention: "5",
        pageSize: 50
      })
    ])
    let ghser: any = {}
    gettiye.forEach((res) => {
      // if (res.code === 10000) {
      if (!res.data) {
        return
      }
      if (ghser.data && ghser.data.length) {
        ghser.data = [...ghser.data, ...res.data]
      } else {
        ghser = res
      }
    })

    if (ghser.data && ghser.data.length) {
      setSearchWord(ghser.data)
    } else {
      setSearchWordMsg(ghser.msg)
    }
    getJiebaApiData(props.goodsName).then((jfr) => {
      setTitleJfrStart(jfr)
    })
    const goodsData = await getGoodsDetells({
      product_id: props.goodid
    }).finally(() => {
      // setDataLodin(false)
      // setGoodPrettifyStatus(true)
    })
    if (goodsData.code === 10000) {
      const deteilsData = goodsData.data.description
      // console.log('获取商品视频ID', goodsData.data.material_video_id)
      if (goodsData.data.material_video_id) {
        const getVidContents = await getVideoDetail({ vid: goodsData.data.material_video_id })
        const getContyers: any = await getVideoDetailNewApi(getVidContents.data.play_auth_token)
        // console.log('getContyers', getContyers)
        goodsData.data.videoDatas = {
          CoverUrl: getContyers.Result.Data.CoverUrl,
          PlayInfo: getContyers.Result.Data.PlayInfoList[0]
        }
      } else {
        goodsData.data.videoDatas = {
          CoverUrl: '',
          PlayInfo: {}
        }
      }

      const prettify_info: string[] = []
      deteilsData.split('src="').forEach((res) => {
        // console.log('ee', res.split("\" style=\""))
        const spliteUrls = res.split('" style="')
        spliteUrls.forEach((item) => {
          if (item.includes("https") || item.includes("http")) {
            prettify_info.push(item.replace('http:///"', '').replace('/"/', ''))
          }
        })
      })
      setGoodPrettify(prettify_info)
      const { fourth_cid, third_cid, second_cid, first_cid } =
        goodsData.data.category_detail
      goodsData.data.category_leaf_id_gt =
        fourth_cid || third_cid || second_cid || first_cid
      const getRuleData = await getProductUpdateRuleData(
        goodsData.data.category_leaf_id_gt
      )
      if (getRuleData.code === 10000) {
        // console.log('getRuleData', getRuleData)
        setRuleData(getRuleData.data)
      }
      const getBer = await getCatePropertyV2Api(
        goodsData.data.category_leaf_id_gt
      ) // 可用品牌列表
      let getBrandListData: any = await getBrandList({
        category_id: goodsData.data.category_leaf_id_gt
      })

      const sheacBrandList = await getBrandList({
        category_id: goodsData.data.category_leaf_id_gt,
        brand_ids: [goodsData.data.standard_brand_id]
      })
      // console.log("sheacBrandList", sheacBrandList)

      // console.log('品牌列表', getBrandListData)

      setDataLodin(false)
      setGoodPrettifyStatus(true)
      let addconterNew = JSON.parse(goodsData.data.product_format_new)
      addconterNew.addRequData = []
      goodsData.data.newprodata = []
      if (getBer.code === 10000) {
        const ads = getBer.data.data
        // console.log("属性规则", ads)
        // console.log("属性     原本设置", goodsData.data.product_format_new)
        if (
          sheacBrandList &&
          sheacBrandList.code === 10000 &&
          getBrandListData &&
          getBrandListData.code === 10000
        ) {
          if (getBrandListData.data?.auth_brand_list) {
            getBrandListData.data?.auth_brand_list.push(
              ...sheacBrandList.data?.brand_list
            )
          } else {
            getBrandListData.data.auth_brand_list =
              sheacBrandList.data?.brand_list
          }
        }
        try {
          const product_format_new_data = JSON.parse(
            goodsData.data.product_format_new
          )
          // console.log('属性序列化', product_format_new_data)
          if (
            product_format_new_data["1687"] &&
            product_format_new_data["1687"].length
          ) {
            product_format_new_data["1687"][0].Value =
              goodsData.data.standard_brand_id
          }
          ads.forEach((itemPro, indexPro) => {
            const itemInfoData = product_format_new_data[itemPro.property_id]
            // console.log('itemInfoData', itemInfoData)
            // console.log('itemPro', itemPro)
            let getItemProter
            if (
              itemPro.property_id === 1687 &&
              getBrandListData.code === 10000
            ) {
              // console.log('是品牌 添加选项')
              itemPro.options = [
                {
                  value_id: "596120136",
                  name: "无品牌",
                  auto_brand: true
                }
              ]

              getBrandListData.data?.auth_brand_list?.forEach((item) => {
                itemPro.options.push({
                  name: (() => {
                    if (item.name_cn && item.name_en) {
                      return item.name_cn + "/" + item.name_en
                    }
                    if (item.name_cn) {
                      return item.name_cn
                    }
                    if (item.name_en) {
                      return item.name_en
                    }
                  })(),
                  value_id: item.brand_id,
                  auto_brand: true
                })
              })

              getBrandListData.data?.brand_list?.forEach((item) => {
                itemPro.options.push({
                  name: (() => {
                    if (item.name_cn && item.name_en) {
                      return item.name_cn + "/" + item.name_en
                    }
                    if (item.name_cn) {
                      return item.name_cn
                    }
                    if (item.name_en) {
                      return item.name_en
                    }
                  })(),
                  value_id: item.brand_id,
                  auto_brand: false
                })
              })

              if (goodsData.data.standard_brand_id === "596120136") {
                itemPro.Name = "无品牌"
                itemPro.Value = "596120136"
                itemPro.diy = 0
                itemPro.PropertyId = 1687
                itemPro.PropertyName = "品牌"
              } else {
                itemPro.Name = itemPro.options.find((iter) => {
                  return iter.value_id === goodsData.data.standard_brand_id
                })
                itemPro.Value = goodsData.data.standard_brand_id
                itemPro.diy = 0
                itemPro.PropertyId = 1687
                itemPro.PropertyName = "品牌"
              }
            }
            itemPro.seletctList = []
            if (itemInfoData) {
              switch (itemPro.type) {
                case "select":
                  getItemProter = itemInfoData[0]
                  itemPro.Name = getItemProter.Name
                  itemPro.Value = getItemProter.Value
                  itemPro.diy = getItemProter.diy_type
                  // console.log('itemPro', itemPro)

                  if (getItemProter.diy_type == 1) {
                    itemPro.options.unshift({
                      name: getItemProter.Name,
                      value_id: getItemProter.Value,
                      diy: 1
                    })
                    itemPro.options = itemPro.options.sort(
                      (a, b) => a.sequence - b.sequence
                    )
                    // console.log('itemPro.options', itemPro.options)
                  }
                  break
                case "text":
                  getItemProter = itemInfoData[0]

                  itemPro.Name = getItemProter.Name
                  itemPro.Value = getItemProter.Value
                  itemPro.diy = getItemProter.diy_type

                  break
                case "measure":
                  getItemProter = itemInfoData[0]

                  itemPro.Name = getItemProter.Name
                  itemPro.Value = getItemProter.Value
                  itemPro.diy = getItemProter.diy_type
                  //   console.log(
                  //     "itemPro.measure_templates",
                  //     itemPro.measure_templates
                  //   )
                  itemPro.measure_templates.forEach((meaItem, indexmea) => {
                    // console.log('itemInfoData', itemInfoData)
                    const getFindItem =
                      itemInfoData.find(
                        (fI) =>
                          fI.measure_info?.template_id == meaItem.template_id
                      ) || getItemProter
                    // console.log('getFindItemgetFindItem****----****', getFindItem)
                    meaItem.value_modules.forEach((meIte) => {
                      const findvalues = getFindItem.measure_info
                        ? getFindItem.measure_info.values.find(
                          (findMeval) =>
                            findMeval.module_id == meIte.module_id
                        )
                        : getFindItem.tags
                      // console.log('findvalues', findvalues)
                      if (getFindItem.measure_info) {
                        meIte.unit_id = findvalues.unit_id
                        meIte.value = findvalues.value
                      } else {
                        meIte.unit_id = findvalues.measure_unit * 1
                        meIte.value = findvalues.measure_unit_value
                      }

                      // meIte = Object.assign(meIte, findvalues)
                    })
                  })
                  // itemPro.MeasureInfo =  itemInfoData.measure_info
                  break
                case "multi_select":
                  // getItemProter = itemInfoData[0]
                  // console.log('itemInfoDataitemInfoData', itemInfoData)
                  // itemPro.Name = getItemProter.Name
                  // itemPro.Value = getItemProter.Value
                  // itemPro.diy = getItemProter.diy_type
                  itemPro.seletctList =
                    itemInfoData.map((itemTuTu) => {
                      if (itemTuTu.diy_type == 1) {
                        itemTuTu.Value = itemTuTu.Name
                        itemTuTu.diy = itemTuTu.diy_type
                        itemPro.options.unshift({
                          name: itemTuTu.Name,
                          value: itemTuTu.Value,
                          value_id: itemTuTu.Value,
                          diy: 1
                        })
                        return itemTuTu.Value
                      }
                      return itemTuTu.Value
                    }) || []
                  break
                case "multi_value_measure":
                  getItemProter = itemInfoData[0]
                  //   console.log("itemPro", itemInfoData, itemPro, getItemProter)
                  itemPro.Name = getItemProter.Name
                  itemPro.Value = getItemProter.Value
                  itemPro.diy = getItemProter.diy_type
                  itemPro.measure_templates_cu = JSON.parse(
                    JSON.stringify(itemPro.measure_templates)
                  )
                  itemPro.measure_templates = []
                  itemInfoData.forEach((itemse) => {
                    itemPro.measure_templates.push(
                      JSON.parse(
                        JSON.stringify(itemPro.measure_templates_cu[0])
                      )
                    )
                    // itemPro.measure_templates.push({})
                  })
                  itemPro.measure_templates.forEach((meaItem, indexmea) => {
                    // console.log('itemInfoData', itemInfoData)
                    const getFindItem = itemInfoData[indexmea]
                    // console.log('multi_value_measure---getFindItemgetFindItem', getFindItem)
                    // console.log('meaItemmeaItemmeaItem', meaItem)
                    meaItem.value_modules.forEach((meIte) => {
                      // console.log('meIte', meIte)
                      const findvalues = getFindItem.measure_info.values.find(
                        (findMeval) => findMeval.module_id == meIte.module_id
                      )
                      // console.log('findvalues', findvalues)
                      meIte.unit_id = findvalues ? findvalues.unit_id : meIte.units[0].unit_id
                      meIte.value = findvalues ? findvalues.value : ''
                      // meIte = Object.assign(meIte, findvalues)
                    })
                  })
                  // console.log('123465789/*-itemPro', itemPro)
                  break
                default:
                  break
              }
            }
          })
        } catch (error) {
          console.log("error属性格式错误", error)
        }
        setStatsDataList(JSON.parse(JSON.stringify(ads)))
        // console.log('ads', ads)
        // setStatsDataList(JSON.parse(JSON.stringify(getBer.data.data)))
        // console.log('需要的属性裂列表', ads)
        ads &&
          ads.forEach((item, index) => {
            if (item.diy_type === 1) {
              // const jkner = JSON.parse(product_format_new)
              let property_id = item.property_id + ""
              property_id &&
                addconterNew[property_id] &&
                addconterNew[property_id].forEach((sx) => {
                  // console.log('sx', sx, item.options)
                  let luer = item.options.find(
                    (opt) => opt.value_id == sx.Value
                  )
                  // console.log('luer', luer)
                  if (!luer) {
                    sx.diy_type = 1
                  }
                })
            }
            if (item.required) {
              if (item.property_id == 1687) {
                // console.log('品牌情况ID', goodsData.data.standard_brand_id)
              }
              // addconterNew.addRequData.push(item)
              // 类目属性必填
              if (
                !addconterNew[item.property_id + ""] &&
                item.property_id != 1687
              ) {
                // console.log('缺失的属性，需要填写', item)
                addconterNew.addRequData.push(item)
              }
              // console.log('必填项, 检查是否填写， 最总需要报错', item.property_id, item)
            }
            if (item.property_id == 3171 || item.property_name === "货号") {
              console.log('addconterNew', addconterNew)
              const getader = addconterNew[item.property_id + ""]
              goodsData.data.newprodata.push({
                Name: getader ? getader[0].Name : "",
                PropertyId: item.property_id,
                PropertyName: item.property_name,
                Value: getader ? getader[0].Value : 0,
                diy_type: 1,
                measure_info: null
              })
            }
          })
        goodsData.data.addRequData = addconterNew.addRequData
      }

      setGoodsDetellData(goodsData.data)
      dispatch(setGoodsDetell(JSON.parse(JSON.stringify(goodsData.data))))
    }
  }
  return (
    <>
      <Modal
        visible={showNercunM}
        title="提示"
        okText="前往清理"
        cancelText=" 取消"
        onCancel={() => setShowNercunM(false)}
        onOk={() => {
          open("https://fxg.jinritemai.com/ffa/shop/material/creative")
          setShowNercunM(false)
        }}>
        <span
          style={{
            color: "red"
          }}>
          素材库内存不足请前往清理后再进行裂变！！！
        </span>
      </Modal>
      <CopyItemBox
        showCopyBox={showCopyBox}
        setShowCopyBox={setShowCopyBox}
        goodid={props.goodid}
        goodsName={props.goodsName}
        getDataLodin={getDataLodin}
        goodsDetellData={goodsDetellData}
        goodPrettify={goodPrettify}
        goodPrettifyStatus={goodPrettifyStatus}
        titleJfrStart={titleJfrStart}
        searchWord={searchWord}
        searchWordMsg={searchWordMsg}
        ruleData={ruleData}
        statsDataList={statsDataList}
      />
      <Space direction="vertical" size={3} style={{
        textAlign: 'left'
      }}>
        <Button
          type="link"
          size="large"
          style={{
            color: "#23A866"
          }}
          icon={<Icon type="AddIcon" />}
          onClick={() => {
            Agreement().then(() => {
              showConetrBox()
            })
          }}>
          商品裂变

        </Button>
        <Button type="link" icon={<Icon type="AiDrawIcon"></Icon>} onClick={async () => {
          console.log('打开检测')
          dispatch(weiguijianceContent(props.goodid))
        }}>违规检测</Button>
        <Button
          type="primary"
          size="small"
          // style={{
          //   color: "#23A866"
          // }}
          onClick={() => {
            Agreement().then(() => {
              open("https://doulingyang.cn/?Isolation=1")
            })
          }}>
          抖店IP隔离
          {/* <Icon type="AddIcon" /> */}
        </Button>
      </Space>
    </>
  )
}

// 创建dom元素
const PlasmoInline: FC<PlasmoCSUIProps> = (anchor: any) => {
  const elm =
    anchor.anchor?.element.parentNode?.parentNode?.querySelectorAll("div")
  let goodid = ""
  //   let goodTitleData = ""
  let goodTagsData: any[] = []
  let goodsName: any =
    anchor?.anchor?.element?.parentNode?.parentNode?.querySelector(
      "[class*=style_productNameNew]"
    ).textContent
  if (!elm) return
  for (let i = 0; i < elm?.length; i++) {
    const title = elm[i].innerText
    // const goodTitle = elm[i].querySelector("[class*=style_productNameNew]")
    const goodTags: any = elm[i].querySelectorAll(
      '[style="color: rgb(25, 102, 255); background-color: transparent;"]'
    )
    // goodTitle && (goodTitleData = goodTitle.innerHTML)
    if (goodTags && goodTags.length) {
      goodTagsData = []
      for (let i = 0; i < goodTags.length; i++) {
        goodTagsData.push(goodTags[i].innerText)
      }
    }
    if (title.includes("ID:")) {
      goodid = title.split(":")[1]
    }
  }

  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <div className="predlist" >
          <ShowPriceUi goodid={goodid} goodsName={goodsName} />
        </div>
      </PersistGate>
    </Provider>
  )
}

export default PlasmoInline
